package com.mall.seckill_mall.interceptor;

import com.mall.seckill_mall.annotations.AccessLimit;
import com.mall.seckill_mall.common.RedisPreffix;
import com.mall.seckill_mall.entity.User;
import com.mall.seckill_mall.enums.CodeMessage;
import com.mall.seckill_mall.exception.SeckillException;
import com.mall.seckill_mall.exception.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request
            , HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length <= 0) {
            throw new UserException(CodeMessage.PLEASE_LOGIN);
        }
        String token = null;
        for (Cookie cookie : cookies) {
            if("user_token".equals(cookie.getName())) {
                token = cookie.getValue();
                break;
            }
        }
        if(token == null) {
            throw new UserException(CodeMessage.PLEASE_LOGIN);
        }
        User user = (User) redisTemplate.opsForValue().get(RedisPreffix.ONLINE_USER_PREFFIX.concat(token));
        if(user == null) {
            throw new UserException(CodeMessage.PLEASE_LOGIN);
        }
        refreshLoginStatus(response, token, user); //刷新登录状态
        if(handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null) {
                return true;
            }
            int period = accessLimit.period();
            int maxCount = accessLimit.maxCount();
            String url = request.getRequestURI();
            String limitKey = RedisPreffix.LIMIT_REQUEST_COUNT.concat(user.getUserId()).concat("_").concat(url);
            Integer count = (Integer) redisTemplate.opsForValue().get(limitKey);
            if(count == null) {
                redisTemplate.opsForValue().set(limitKey, 1, period, TimeUnit.SECONDS);
                return true;
            }
            if(count >= maxCount) {
                throw new SeckillException(CodeMessage.LIMIT_REQUEST);
            }
            redisTemplate.opsForValue().increment(limitKey);
        }
        return true;
    }

    private void refreshLoginStatus(HttpServletResponse response, String token, User user) {
        Cookie cookie = new Cookie("user_token", token);
        cookie.setMaxAge(30 * 60);
        cookie.setPath("/");
        response.addCookie(cookie);
        redisTemplate.opsForValue().set(RedisPreffix.ONLINE_USER_PREFFIX.concat(token), user, 30, TimeUnit.MINUTES);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
